package com.lee.boot.head.first.demo.controller;


import com.lee.boot.head.first.demo.entity.UserEntity;
import com.lee.boot.head.first.demo.repository.UserRepository;
import com.lee.boot.head.first.demo.service.UserEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;
import java.util.Map;

/**
 * @Auther: Lee
 * @Date: 2018/4/27 16:33
 * @Description: 返回json数据的接口
 */
//使用restController注解会使该类所有接口返回的都是接口json数据
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserEntityService userEntityService;
    @Autowired
    UserRepository userRepository;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<UserEntity> list() {
        List<UserEntity> all = userEntityService.findAll();
//        model.addAllAttributes(all);
//        model.put("add",all);

        //直接返回查询结果
        return all;
    }
    //modandview在这不管用
//    public ModelAndView list(ModelAndView modelAndView) {
//        List<UserEntity> all = userService.findAll();
//        modelAndView.addObject(all);
//
//        return modelAndView;
//    }


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public List<UserEntity> add(UserEntity userEntity, Map<String, Object> map) {
        UserEntity add = userEntityService.add(userEntity);
        map.put("add", add);
        return userEntityService.findAll();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public List<UserEntity> delete(Long id) {
        userEntityService.delete(id);
        return userEntityService.findAll();
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public UserEntity update(UserEntity userEntity) {
//        if (null == userEntity.getId() || userEntity.equals("")) {
//            return null;
//        }
        return userEntityService.update(userEntity);
    }

    @RequestMapping(value = "/getByname")
    public List<UserEntity> getByName(String name) {
        return userEntityService.getByName(name);
    }

    public List<UserEntity> getByName(String name, Integer page) {
        PageRequest pageRequest = PageRequest.of(page, 2);
        //使用构造器生成对象已经过时 推荐使用上面的of方法生成对象
//        PageRequest pageRequest = new PageRequest(page, 2);
        return userRepository.findAll(pageRequest).getContent();

    }


    public UserEntityService getUserEntityService() {
        return userEntityService;
    }

    public void setUserEntityService(UserEntityService userEntityService) {
        this.userEntityService = userEntityService;
    }
}
